package com.example.plus5;

import android.text.format.Time;
import android.widget.TextView;
import java.net.MalformedURLException;
import java.util.Scanner;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import java.util.ArrayList;
import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
import android.view.View;

public class Home extends Activity {

	private String destination, time, school;
	private ArrayList<String> arrayOfAttributes;
	private Time alarm = new Time();


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		doTheStuffs();
		setContentView(R.layout.activity_home);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.home, menu);
		Intent intent = getIntent();
		String string_msg = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

		String [] message = string_msg.split("-");

		destination = message[0];
		time = message[1];
		school = message[2];


		return true;
	}

	public void openAlarm(View view) {
		Intent intent = new Intent(this, Alarm.class);
		//Here is where the alarm would have been adjusted

		startActivity(intent);
	}

	public void openWeather(View view) {
		Intent intent = new Intent(this, Weather.class);
		startActivity(intent);
	}

	public void openSchool(View view) {
		Intent intent = new Intent(this, School.class);
		startActivity(intent);
	}
	public void viewAppointments(View v){
		Intent intent = new Intent(this,Appointments.class);
		startActivity(intent);
	}

	private void doTheStuffs() {
	    try {

	        /** Create a new textview array to display the results */
	        TextView weather[];
	        TextView fullCity[];
	        TextView temperature[];
	        TextView windGust[];
	        TextView heatIndex[];
	        TextView feelsLike[];
	        TextView precipitation[];
	        TextView testArrayList[];
	        TextView htmlView[];
	        TextView durationView[];

            String state = "CA";
            String city = "San_Francisco"; //City must be in this format

            URL url = new URL("http://api.wunderground.com/api/f74c3eadb26412d6/conditions/q/"+ state + "/" + city + ".xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();

            NodeList currentObservation = doc.getElementsByTagName("current_observation"); //Everything within current observation nodelist

            /** Assign textview array lenght by arraylist size */
            arrayOfAttributes = new ArrayList<String>();
            weather = new TextView[currentObservation.getLength()];
            temperature = new TextView[currentObservation.getLength()];
            windGust = new TextView[currentObservation.getLength()];
            heatIndex = new TextView[currentObservation.getLength()];
            feelsLike = new TextView[currentObservation.getLength()];
            precipitation = new TextView[currentObservation.getLength()];
            htmlView = new TextView[currentObservation.getLength()];

            for (int i = 0; i < currentObservation.getLength(); i++) {

                Node node = currentObservation.item(i);

                weather[i] = new TextView(this);

                Element fstElmnt = (Element) node;
                NodeList weatherList = fstElmnt.getElementsByTagName("weather");
                Element weatherElement = (Element) weatherList.item(0);
                weatherList = weatherElement.getChildNodes();
                arrayOfAttributes.add("Weather:" + ((Node)weatherList.item(0)).getNodeValue()); //Add attribute to arrayList


                temperature[i] = new TextView(this);

                NodeList temperatureList = fstElmnt.getElementsByTagName("temp_f");
                Element termperatureElement = (Element) temperatureList.item(0);
                temperatureList = termperatureElement.getChildNodes();
                arrayOfAttributes.add("Temperature:" + ((Node)temperatureList.item(0)).getNodeValue());


                windGust[i] = new TextView(this);

                NodeList windGustList = fstElmnt.getElementsByTagName("wind_gust_mph");
                Element windGustElement = (Element) windGustList.item(0);
                windGustList = windGustElement.getChildNodes();
                arrayOfAttributes.add("Wind Gust:" + ((Node)windGustList.item(0)).getNodeValue());


                heatIndex[i] = new TextView(this);
                NodeList heatIndexList = fstElmnt.getElementsByTagName("heat_index_f");
                Element heatIndexElement = (Element) heatIndexList.item(0);
                heatIndexList = heatIndexElement.getChildNodes();
                arrayOfAttributes.add("Heat Index:" + ((Node)heatIndexList.item(0)).getNodeValue());


                feelsLike[i] = new TextView(this);
                NodeList feelsLikeList = fstElmnt.getElementsByTagName("feelslike_f");
                Element feelsLikeElement = (Element) feelsLikeList.item(0);
                feelsLikeList = feelsLikeElement.getChildNodes();
                arrayOfAttributes.add("Feels Like:" + ((Node)feelsLikeList.item(0)).getNodeValue());


                precipitation[i] = new TextView(this);
                NodeList precipitationList = fstElmnt.getElementsByTagName("precip_today_in");
                Element precipitationElement = (Element) precipitationList.item(0);
                precipitationList = precipitationElement.getChildNodes();
                arrayOfAttributes.add("Precipitation:" + ((Node)precipitationList.item(0)).getNodeValue());


                htmlView[i] = new TextView(this);
                String htmlOut = (new Scanner(new URL("http://glasswaretesting.droppages.com/schoolOpeningTimes.html").openStream(), "UTF-8").useDelimiter("\\A").next());
                htmlView[i].setText(htmlOut);
                if (htmlOut.contains("Gaithersburg High School - closed")) {
                    htmlView[i].setText("Gaithersburg High School is closed.");
                } else {
                    htmlView[i].setText("Gaithersburg High School is open.");
                }

            }

            NodeList displayLocation = doc.getElementsByTagName("display_location");

            /** Assign textview array length by arraylist size */
            fullCity = new TextView[displayLocation.getLength()];
            testArrayList = new TextView[displayLocation.getLength()];
            durationView = new TextView[displayLocation.getLength()];

            for (int i = 0; i < displayLocation.getLength(); i++) {

                Node node = displayLocation.item(i);

                fullCity[i] = new TextView(this);

                Element fstElmnt = (Element)node;

                NodeList fullCityList = fstElmnt.getElementsByTagName("full");
                Element fullCityElement = (Element) fullCityList.item(0);
                fullCityList = fullCityElement.getChildNodes();
                fullCity[i].setText("City = " + ((Node) fullCityList.item(0)).getNodeValue());



            }

            testArrayList[0] = new TextView(this);
            testArrayList[0].setText("Array: " + arrayOfAttributes.toString());
            //Set modulus to account for 1 inch

            long duration = returnRouteDuration("13321 Rushing Water Way Germantown MD 20874", "Kingsview Giant");
            durationView[0] = new TextView(this);
            durationView[0].setText(Long.toString(duration) + " minutes");
            //Set modulus to account for 1 inch


        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

        /** Set the layout view to display */


    }

    public int returnDangerValue () {
        int count = 0;

        for (String s: arrayOfAttributes) {
            if (s.equals("chance")) {
                count+=2;
            } else if (s.equalsIgnoreCase("rain") || s.equalsIgnoreCase("storm") || s.equalsIgnoreCase("showers")){
                count+=4;
            } else if (s.equalsIgnoreCase("snow") || s.equalsIgnoreCase("sleet") || s.equalsIgnoreCase("ice")) {
                count+=7;
            } else if (s.equalsIgnoreCase("temp_below")) {
                count++;
            }
        }

        return count;
    }

    public long returnRouteDuration (String origin, String destination) {
        long totalDuration = 0;
        //Needs origin, destination and sensor at least. For this app's sake sensor is false.
        //Pass in parameters into url to generate xml file. No api key required for this part.
        //Example url: http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Vancouver+BC&mode=bicycling&language=fr-FR&sensor=false
        //Place & between each parameter
        String stringURL = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins="+ origin + "&destinations=" + destination + "&mode=driving&language=en-EN&sensor=false";
        try {
            URL customizedURL = new URL("http://maps.googleapis.com/maps/api/distancematrix/xml?origins=13321%20Rushing%20Water%20Way%20Germantown%20MD&destinations=21261%20Owls%20Nest%20Circle%20Germantown%20MD&mode=driving&language=en-EN&sensor=false");
            try {
                TextView routeDuration[];
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(new InputSource(customizedURL.openStream()));
                doc.getDocumentElement().normalize();

                NodeList duration = doc.getElementsByTagName("duration"); //Everything within current observation nodelist

                for (int i = 0; i < duration.getLength(); i++) {

                    Node node = duration.item(i);

                    routeDuration = new TextView[duration.getLength()];
                    routeDuration[i] = new TextView(this);


                    Element fstElmnt = (Element) node;
                    NodeList textList = fstElmnt.getElementsByTagName("text");
                    Element weatherElement = (Element) textList.item(0);
                    textList = weatherElement.getChildNodes();
                    totalDuration+=Long.parseLong((((Node) textList.item(0)).getNodeValue()).substring(0, 2));
                }
            } catch (Exception e) {
                System.out.println("XML Parsing Exception = " + e);
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return totalDuration;


	}
}
